<template>
  <div>
    <el-dialog
      v-model="upload.open"
      :close-on-click-modal="false"
      :title="upload.title"
      append-to-body
      width="400px"
    >
      <el-upload
        ref="uploadRef"
        :action="upload.url"
        :auto-upload="false"
        :before-upload="handleBeforeUpload"
        :disabled="upload.isUploading"
        :headers="upload.headers"
        :limit="1"
        :on-success="handleFileSuccess"
        accept=".xlsx, .xls"
        drag
        :data="data"
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>

        <template #tip v-if="downloadUrl">
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              type="primary"
              @click="importTemplateFun"
              >下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
      <div v-if="upload.isUploading && percentage > 0" style="margin-top: 20px">
        <el-progress :percentage="percentage" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            :loading="upload.isUploading"
            type="primary"
            @click="submitFileForm"
            >确 定</el-button
          >
          <el-button :disabled="upload.isUploading" @click="cancelClick()"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth";
import { useUserStore } from "@/stores/user";
import { ref,computed ,getCurrentInstance ,reactive,onBeforeUnmount,nextTick  } from "vue";

const userStore = useUserStore();

const emit = defineEmits();
const props = defineProps({
  downloadUrl: {
    type: String,
    default: "",
  },
  importUrl: {
    type: String,
    default: "",
  },
  title: {
    type: String,
    default: "",
  },
  isBatchSetType: {
    type: Boolean,
    default: false,
  },
});
const percentage = ref(0);
const batchSetType = ref("10");
const isRepeat = ref("N");

const { proxy } = getCurrentInstance();
/*** 客户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_API_URL + props.importUrl,
});

/**请求额外参数*/
const data = computed(() => {
  let result;
  if (props.isBatchSetType) {
    result = { type: batchSetType.value };
  } else {
    result = {};
  }
  if (props.title === "客户档案") {
    result.isRepeat = isRepeat.value;
  }

  return result;
});
let webSocket = null;
const initWebSocket = () => {
  const wsUrl = userStore.socketUrl + "/revenue/websocket/" + userStore.id;
  webSocket = new WebSocket(wsUrl);
  webSocket.onopen = () => {
    console.log("onopen-ok");
  };
  webSocket.onmessage = (e) => {
    if (e.data) {
      const data = JSON.parse(e.data);
      if (data.total && data.current) {
        percentage.value = Math.round((data.current / data.total) * 100);
      }
    }
  };

  webSocket.onerror = (e) => {
    console.error("onerror", e);
  };
  webSocket.onclose = () => {
    console.log("onclose");
  };
};

const clearWebSocket = () => {
  if (webSocket) {
    webSocket.close();
    webSocket = null;
  }
};

const cancelClick = () => {
  upload.open = false;
  clearWebSocket();
  upload.isUploading = false;
  percentage.value = 0;
};

/** 导入按钮操作 */
function handleImport(val) {
  upload.isUploading = false;
  percentage.value = 0;
  if (val) {
    upload.url = import.meta.env.VITE_APP_API_URL + val;
  }
  upload.title = `${props.title}导入`;
  upload.open = true;
  nextTick(() => {
    proxy.$refs["uploadRef"].clearFiles();
  });
  initWebSocket();
}

/** 下载模板操作 */
function importTemplateFun() {
  proxy.download(props.downloadUrl, {}, `${props.title}导入模版.xlsx`);
}

const handleBeforeUpload = () => {
  upload.isUploading = true;
  percentage.value = 0;
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

/** 文件上传成功处理 */
const handleFileSuccess = (response) => {
  cancelClick();
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      "</div>",
    "导入结果",
    {
      dangerouslyUseHTMLString: true,
      showCancelButton: response.msg === "部分导入失败",
      confirmButtonText: "确定",
      cancelButtonText: "下载失败数据",
      beforeClose: (action, instance, done) => {
        if (action === "cancel" && response.msg === "部分导入失败") {
          window.open(
            import.meta.env.VITE_APP_API_URL +
              "/profile/download/" +
              response.data
          );
        }
        done();
      },
    }
  );
  if (props.isBatchSetType) {
    emit("loadList", response);
  } else {
    emit("loadList", true);
  }
};

onBeforeUnmount(() => {
  clearWebSocket();
});

defineExpose({ handleImport, batchSetType });
</script>
